from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.urls import reverse

from .search import 查询

from .models import 销售入账记录, 对话记录


def newtalk(request):
    未结束的对话 = 对话记录.objects.filter(已结束=False)
    for current in 未结束的对话:
        current.已结束 = True
    对话记录.objects.bulk_update(未结束的对话, ['已结束'])
    return redirect(reverse('home:index'))


def index(request):
    # return HttpResponse("home index")
    用户输入 = request['POST']
    查询参数 = 获取结构化数据查询参数(用户输入)
    查询结果 = None
    if 查询参数 is not None:
        查询结果 = 查询(查询参数)
    if 查询结果 is None:
        从数据库查不到相关数据时的操作()
    else:
        根据查询结果回答用户输入(查询结果, 用户输入)
    conversation_list = 对话记录.objects.filter(已结束=False).order_by('created_time')
    return render(request, "home/index.html", {"object_list": conversation_list})


def salescheck(request):
    # return HttpResponse("home index")
    if request.method == 'POST':
        客户 = request.POST['name']
        if 客户 is not None or 客户.strip() != '':
            object_list = 查询({'模块': '销售对账', '客户名称': 客户})
        else:
            object_list = 销售入账记录.objects.all()
    else:
        object_list = 销售入账记录.objects.all()

    return render(request, "home/salescheck.html", context={"object_list": object_list})


def 获取结构化数据查询参数(用户输入):
    return None


def 从数据库查不到相关数据时的操作():
    record = 对话记录()
    record.role = "assistant"
    record.处理后content = "抱歉，数据库里面没有你需要的信息。"
    record.不带入大模型对话中 = False
    record.save()


def 根据查询结果回答用户输入(查询结果, 用户输入):
    return None


def addsalescheck(request):
    if request.method == 'POST':
        record = 销售入账记录()
        record.客户 = request.POST['name']
        record.入账日期 = request.POST['created_at']
        record.入账金额 = request.POST['amount']
        record.已到账款项 = request.POST['total']
        record.剩余到账款项 = request.POST['leave']

        record.save()
        return redirect(reverse('home:salescheck'))
    else:
        return render(request, "home/addsalescheck.html")
